/**
 * Copyright (c) 2005-2010 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: ConvertUtils.java,v 1.1 2013/07/23 06:17:04 qiujiwei Exp $
 */
package utils.commons;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.ClassConverter;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.reflect.ConstructorUtils;

public class ConvertUtils {

	static {
		registerDateConverter();
	}

	/**
	 * 提取集合中的对象的属性(通过getter函数), 组合成List.
	 * 
	 * @param collection 来源集合.
	 * @param propertyName 要提取的属性名.
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static List convertElementPropertyToList(final Collection collection, final String propertyName) {
		List list = new ArrayList();

		try {
			for (Object obj : collection) {
				list.add(PropertyUtils.getProperty(obj, propertyName));
			}
		} catch (Exception e) {
			throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
		}

		return list;
	}

	/**
	 * 提取集合中的对象的属性(通过getter函数), 组合成由分割符分隔的字符串.
	 * 
	 * @param collection 来源集合.
	 * @param propertyName 要提取的属性名.
	 * @param separator 分隔符.
	 */
	@SuppressWarnings("rawtypes")
  public static String convertElementPropertyToString(final Collection collection, final String propertyName,
			final String separator) {
		List list = convertElementPropertyToList(collection, propertyName);
		return StringUtils.join(list, separator);
	}

	/**
	 * 转换字符串到相应类型.
	 * 
	 * @param value 待转换的字符串.
	 * @param toType 转换目标类型.
	 */
	@SuppressWarnings("deprecation")
  public static Object convertStringToObject(String value, Class<?> toType) {
		try {
			if (toType.toString().equals("class java.util.Date")){
				String dateString = value;
				if (dateString.contains("下午")) {
					String yearday=dateString.substring(0,10);
					int pos=dateString.indexOf(":");
					int hour=(new Integer(dateString.substring(pos-2,pos))+12);
					String hourtime=hour+ dateString.substring(pos, dateString.length());
					dateString=yearday+hourtime;
				}
				if (dateString.contains("上午")) {
					String yearday=dateString.substring(0,10);
					int pos=dateString.indexOf(":");
					int hour=(new Integer(dateString.substring(pos-2,pos)));
					String hourtime=hour+ dateString.substring(pos, dateString.length());
					dateString=yearday+hourtime;
				}
				value=dateString;
				if (value.contains("CST")) {
					value = value.replace("CST", "GMT+800");
				}
				if (value.contains("GMT 800")) {
					value = value.replace("GMT 800", "GMT+800");
				}
				if (value.contains("GMT+800")) {
					return new Date(value); 
				}
				else{ 
					if(value.indexOf("/")==2){
						value = value.replace("/", "-");
						value=value.substring(6, 10)+"-"+value.substring(0,5);					
					}
					boolean issmartgwtclient = value.contains("T");
//					if (issmartgwtclient){
						value = value.replace('T', ' ');
						if (value != null) {
							// 处理传过来没有时间的日期参数
							if (value.indexOf(":") == -1) {
								value = value + " 00:00:00";
							} 
							SimpleDateFormat format = new SimpleDateFormat(
									"yyyy-MM-dd HH:mm:ss",Locale.SIMPLIFIED_CHINESE);
							
		//Start ---Add by liaojc at 2012-12-13  解决 日期格式“2012/12/12 00:00:00”引起的错误 ，改为“2012-12-12 00:00:00”格式
//							String s4=value.substring(4, 5);
//							String s7=value.substring(7, 8);
							if(value.substring(4, 5).equals("/") && value.substring(7, 8).equals("/")){
								String s[] = value.split("/");
								value=s[0]+"-"+s[1]+"-"+s[2];
							}
												
		//End ---
							java.util.Date _datetime = format.parse(value);
							if(issmartgwtclient){
								Calendar calendar = Calendar.getInstance(); 
								calendar.setTime(_datetime);
								calendar.add(Calendar.HOUR, 8);
								_datetime = calendar.getTime();
							}
							return new Date(_datetime.getTime()); 
						}
//					}
//					else{
//						return org.apache.commons.beanutils.ConvertUtils.convert(value, toType);
//					}
				}	 
			}
			return org.apache.commons.beanutils.ConvertUtils.convert(value, toType);
		} catch (Exception e) {
			throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
		}
	}

	/**
	 * 定义日期Converter的格式: yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss
	 */
	private static void registerDateConverter() {
		DateConverter dc = new DateConverter();
		dc.setUseLocaleFormat(true);
		dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" });
		org.apache.commons.beanutils.ConvertUtils.register(dc, Date.class);
	}
	
  /**
   * convertToType方法：类型转换工具，将输入的对象转换为指定的类型。<br/>
   * 将org.apache.commons.beanutils.converters.ClassConverter的转换方法进行了增强。<br/>
   * @param type  需要转换的目的类型
   * @param value 需要类型转换的对象
   * @return 转换成目的类型后的对象
   * @author leeo
   * @exception Exception
   */
  public static Object convertToType(Class<?> type, Object value){
    if( null==value || value.getClass().equals(type)  || type.isInstance(value))
      return value;
    
    if(null != ConstructorUtils.getAccessibleConstructor(type, value.getClass())){
      try {
        return ConstructorUtils.invokeConstructor(type, value);
      } catch (Exception e) {
        //已经检查是否存在可用的构造函数，所以不会出现相关异常
      }
    }
    
    if(value.getClass().equals(BigDecimal.class)){
      if(type.equals(long.class)||type.equals(Long.class))
        return ((BigDecimal)value).longValue();
      else if(type.equals(double.class)||type.equals(Double.class))
        return ((BigDecimal)value).doubleValue();
      else if(type.equals(float.class)||type.equals(Float.class))
        return ((BigDecimal)value).floatValue();
      else if(type.equals(int.class)||type.equals(Integer.class))
        return ((BigDecimal)value).intValue();
      else if(type.equals(short.class)||type.equals(Short.class))
        return ((BigDecimal)value).shortValue();
      else if(type.equals(byte.class)||type.equals(Byte.class))
        return ((BigDecimal)value).byteValue();
    }
    
    if(type.equals(BigDecimal.class)){
      if(value.getClass().equals(long.class)||value.getClass().equals(Long.class)){
        return new BigDecimal((Long)value);
      }else if(value.getClass().equals(int.class)||value.getClass().equals(Integer.class)){
        return new BigDecimal((Integer)value);
      }else if(value.getClass().equals(BigInteger.class)){
        return new BigDecimal((BigInteger)value);
      }else if(value.getClass().equals(String.class)){
        return new BigDecimal((String)value);
      }else if(value.getClass().equals(double.class)||value.getClass().equals(Double.class)){
        return new BigDecimal(((Double)value).toString());
      }else if(value.getClass().equals(float.class)||value.getClass().equals(Float.class)){
        return new BigDecimal(((Float)value).toString());
      }
    }
    
    return new ClassConverter().convert(type, value);
  }
}
